package com.lnj.controller;

import com.lnj.service.FileDeduplicationService;
import com.lnj.utils.FileTypeValidator;
import com.lnj.utils.ResponseResult;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
public class FileUploadController {
    @Autowired
    private FileDeduplicationService fileDeduplicationService;

    /**
     * 上传文件（支持批量）
     * POST /api/files/upload
     */
    @PostMapping("/upload")
    public ResponseResult<?> uploadFiles(
            @RequestPart("uploadFiles") MultipartFile[] uploadFiles
    ) {
        // 1. 校验空文件列表
        if (uploadFiles == null || uploadFiles.length == 0) {
            return ResponseResult.builder().code(0).msg("上传文件不能为空").build();
        }

        // 2. 处理每个文件
        StringBuilder sbs=new StringBuilder();
        StringBuilder sbf=new StringBuilder("失败:");
        List<String> successUrls = new ArrayList<>();

        for (MultipartFile file : uploadFiles) {
            String originalFilename = file.getOriginalFilename();
            if (file.isEmpty()) {
                sbf.append(originalFilename).append(":").append("文件为空，");
                continue;
            }

            try (InputStream is = file.getInputStream()) {
                // 校验文件类型
                if (!FileTypeValidator.isValidFileType(file.getContentType(), originalFilename, is)) {
                    sbf.append(originalFilename).append(":").append("文件类型不支持，");
                    continue;
                }

                // 上传文件
                String fileUrl = fileDeduplicationService.processAndGetFileUrl(file);
                successUrls.add(fileUrl);
                if (successUrls.size()==1){
                    sbs.append(fileUrl);
                }
                sbs.append(",").append(fileUrl);
                log.info("文件上传成功: {}", originalFilename);
            } catch (Exception e) {
                log.error("文件上传失败: {}", originalFilename, e);
                sbf.append(originalFilename).append(":").append("上传失败" + e.getMessage()).append("，");
            }
        }

        // 3. 构造返回结果
        if (successUrls.size() == uploadFiles.length) {
            // 全部成功
            return ResponseResult.ok(1, "所有文件上传成功").setData(successUrls);
        } else if (!successUrls.isEmpty()) {
            // 部分成功
            sbs.append(sbf.toString());
            return ResponseResult.ok(0, "部分文件上传成功").setData(sbs.toString());
        } else {
            // 全部失败
            return ResponseResult.error(2, "所有文件上传失败").setData(sbf.toString());
        }
    }
}